import { atom } from 'jotai'
import { atomWithStorage } from 'jotai/utils'
import { Assistant, storageKeys } from '@/types'

const currentAssistantIdStorage = atomWithStorage<string | null>(storageKeys.AssistantId, null)
export const assistantListAtom = atomWithStorage<Assistant[]>(storageKeys.Assistants, [])

export const currentAssistantIdAtom = atom(
  (get) => {
    const storedId = get(currentAssistantIdStorage)
    const assistants = get(assistantListAtom)
    if (storedId && assistants.some(assistant => assistant.id === storedId)) {
      return storedId
    }
    return assistants.length > 0 ? assistants[0].id : null
  },
  (get, set, update) => {
    const ov = get(currentAssistantIdStorage)
    const nv = typeof update === 'function' ? update(ov) : update
    set(currentAssistantIdStorage, nv)
  },
)

export const currentAssistantAtom = atom(
  (get) => {
    const id = get(currentAssistantIdAtom)
    const assistants = get(assistantListAtom)
    const current = assistants.find(assistant => assistant.id === id)
    return current ? current : null
  },
)

export const defaultPrompt = 'You are a helpful assistant. You can help me by answering my questions. You can also ask me questions.'
